package com.schoolhelper.model.dao.jsonparse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.schoolhelper.model.dao.okhttp.RequestUtil;
import com.schoolhelper.utils.constant.MessageConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class EasyCodeJsonParser implements JsonParser {

    private static final String OK_MSG = RequestUtil.OK_MSG;

    @Override
    public <T> List<T> getList(String responseData, Class<T> resultVoClass) {
        List<T> list = new ArrayList<>();
        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        if (OK_MSG.equals(responseJson.get("msg"))) {
            JSONObject dataJson = (JSONObject) responseJson.get("data");
            if (dataJson != null) {
                JSONArray recordsArray = (JSONArray) dataJson.get("records");
                for (int i = 0; i < Objects.requireNonNull(recordsArray).size(); i++) {
                    JSONObject data = recordsArray.getJSONObject(i);
                    list.add(JSON.parseObject(String.valueOf(data), resultVoClass));
                }
            } else {
                System.out.println("error: " + "数据库中无对应数据");
            }
        } else {
            System.out.println("error: " + responseJson.get("error"));
        }
        return list;
    }

    @Override
    public <T> T getOne(String responseData, Class<T> resultVoClass) {
        T res = null;
        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        if (OK_MSG.equals(responseJson.get("msg"))) {
            JSONObject dataJson = (JSONObject) responseJson.get("data");
            if (dataJson != null) {
                res = JSON.parseObject(String.valueOf(dataJson), resultVoClass);
            } else {
                System.out.println("error: " + "数据库中无对应数据");
            }
        } else {
            System.out.println("error: " + responseJson.get("error"));
        }
        return res;
    }

    @Override
    public boolean getCode(String responseData) {
        System.out.println(responseData);
        JSONObject responseJson = (JSONObject) JSONObject.parse(responseData);
        return OK_MSG.equals(responseJson.get("msg"));
    }
}
